import { 
  IntelligenceReport, 
  Insight, 
  Recommendation, 
  DataPoint, 
  Transaction,
  BehaviorInsight,
  MarketImpact,
  AddressProfile
} from '../../types';
import { createModuleLogger } from '../../utils/logger';
import { DatabaseService } from '../database/DatabaseService';

const logger = createModuleLogger('report-generation');

export class ReportGenerationService {
  private static instance: ReportGenerationService;
  private dbService: DatabaseService;
  private reportCache = new Map<string, IntelligenceReport>();

  private constructor(dbService: DatabaseService) {
    this.dbService = dbService;
  }

  public static getInstance(dbService: DatabaseService): ReportGenerationService {
    if (!ReportGenerationService.instance) {
      ReportGenerationService.instance = new ReportGenerationService(dbService);
    }
    return ReportGenerationService.instance;
  }

  /**
   * 生成交易分析报告
   */
  public async generateTransactionAnalysisReport(transaction: Transaction): Promise<IntelligenceReport> {
    try {
      logger.info(`生成交易分析报告: ${transaction.hash}`);

      const insights = await this.analyzeTransactionInsights(transaction);
      const recommendations = await this.generateTransactionRecommendations(transaction, insights);
      const dataPoints = await this.collectTransactionDataPoints(transaction);

      const report: IntelligenceReport = {
        id: `tx_report_${Date.now()}`,
        title: `大额交易分析报告 - $${transaction.valueUSD.toLocaleString()}`,
        summary: await this.generateTransactionSummary(transaction, insights),
        type: 'transaction_analysis',
        insights,
        recommendations,
        dataPoints,
        generatedAt: new Date(),
        confidence: this.calculateOverallConfidence(insights),
        tags: this.generateTransactionTags(transaction)
      };

      logger.info(`交易分析报告生成完成: ${transaction.hash}`);
      return report;

    } catch (error) {
      logger.error(`生成交易分析报告失败 ${transaction.hash}:`, error);
      throw error;
    }
  }

  /**
   * 生成模式发现报告
   */
  public async generatePatternDiscoveryReport(
    patterns: any[], 
    address: string
  ): Promise<IntelligenceReport> {
    try {
      logger.info(`生成模式发现报告: ${address}`);

      const insights = await this.analyzePatternInsights(patterns, address);
      const recommendations = await this.generatePatternRecommendations(patterns, insights);
      const dataPoints = await this.collectPatternDataPoints(patterns);

      const report: IntelligenceReport = {
        id: `pattern_report_${Date.now()}`,
        title: `地址行为模式分析 - ${address.substring(0, 8)}...`,
        summary: await this.generatePatternSummary(patterns, insights),
        type: 'pattern_discovery',
        insights,
        recommendations,
        dataPoints,
        generatedAt: new Date(),
        confidence: this.calculateOverallConfidence(insights),
        tags: this.generatePatternTags(patterns)
      };

      logger.info(`模式发现报告生成完成: ${address}`);
      return report;

    } catch (error) {
      logger.error(`生成模式发现报告失败 ${address}:`, error);
      throw error;
    }
  }

  /**
   * 生成市场情报报告
   */
  public async generateMarketIntelligenceReport(timeframe: string = '24h'): Promise<IntelligenceReport> {
    try {
      logger.info(`生成市场情报报告: ${timeframe}`);

      const marketData = await this.collectMarketData(timeframe);
      const insights = await this.analyzeMarketInsights(marketData);
      const recommendations = await this.generateMarketRecommendations(insights);
      const dataPoints = await this.collectMarketDataPoints(marketData);

      const report: IntelligenceReport = {
        id: `market_report_${Date.now()}`,
        title: `市场情报报告 - ${timeframe}`,
        summary: await this.generateMarketSummary(marketData, insights),
        type: 'market_intelligence',
        insights,
        recommendations,
        dataPoints,
        generatedAt: new Date(),
        confidence: this.calculateOverallConfidence(insights),
        tags: ['市场分析', '趋势预测', timeframe]
      };

      logger.info(`市场情报报告生成完成`);
      return report;

    } catch (error) {
      logger.error(`生成市场情报报告失败:`, error);
      throw error;
    }
  }

  /**
   * 生成风险评估报告
   */
  public async generateRiskAssessmentReport(
    addresses: string[], 
    riskFactors: any[]
  ): Promise<IntelligenceReport> {
    try {
      logger.info(`生成风险评估报告: ${addresses.length}个地址`);

      const insights = await this.analyzeRiskInsights(addresses, riskFactors);
      const recommendations = await this.generateRiskRecommendations(insights);
      const dataPoints = await this.collectRiskDataPoints(addresses, riskFactors);

      const report: IntelligenceReport = {
        id: `risk_report_${Date.now()}`,
        title: `风险评估报告 - ${addresses.length}个地址`,
        summary: await this.generateRiskSummary(insights),
        type: 'risk_assessment',
        insights,
        recommendations,
        dataPoints,
        generatedAt: new Date(),
        confidence: this.calculateOverallConfidence(insights),
        tags: ['风险评估', '合规分析', '威胁检测']
      };

      logger.info(`风险评估报告生成完成`);
      return report;

    } catch (error) {
      logger.error(`生成风险评估报告失败:`, error);
      throw error;
    }
  }

  /**
   * 分析交易洞察
   */
  private async analyzeTransactionInsights(transaction: Transaction): Promise<Insight[]> {
    const insights: Insight[] = [];

    // 金额分析
    if (transaction.valueUSD > 100000000) {
      insights.push({
        id: `insight_${Date.now()}_1`,
        type: 'anomaly',
        title: '超大额交易',
        description: `这是一笔价值${transaction.valueUSD.toLocaleString()}美元的超大额交易，可能对市场产生重大影响`,
        impact: 'high',
        confidence: 0.9,
        supportingData: [{ metric: '交易金额', value: transaction.valueUSD }]
      });
    }

    // 地址标签分析
    if (transaction.fromLabel?.type === 'exchange' && transaction.toLabel?.type === 'whale') {
      insights.push({
        id: `insight_${Date.now()}_2`,
        type: 'trend',
        title: '机构资金流向',
        description: `资金从交易所${transaction.fromLabel.label}流向鲸鱼地址，可能表明大户在建仓`,
        impact: 'medium',
        confidence: 0.8,
        supportingData: [
          { metric: '发送方', value: transaction.fromLabel.label },
          { metric: '接收方', value: transaction.toLabel?.label || 'Unknown' }
        ]
      });
    }

    // 时间分析
    const hour = new Date(transaction.timestamp).getHours();
    if (hour >= 2 && hour <= 6) { // 凌晨2-6点
      insights.push({
        id: `insight_${Date.now()}_3`,
        type: 'anomaly',
        title: '非常规时间交易',
        description: `交易发生在凌晨${hour}点，非常规交易时间可能表明特殊意图`,
        impact: 'low',
        confidence: 0.6,
        supportingData: [{ metric: '交易时间', value: `${hour}:00` }]
      });
    }

    return insights;
  }

  /**
   * 生成交易建议
   */
  private async generateTransactionRecommendations(
    transaction: Transaction, 
    insights: Insight[]
  ): Promise<Recommendation[]> {
    const recommendations: Recommendation[] = [];

    const highImpactInsights = insights.filter(i => i.impact === 'high');
    if (highImpactInsights.length > 0) {
      recommendations.push({
        id: `rec_${Date.now()}_1`,
        type: 'monitoring',
        priority: 'high',
        title: '加强监控',
        description: '该交易具有高影响潜力，建议加强后续监控',
        actionItems: [
          '设置价格波动告警',
          '监控相关地址后续活动',
          '关注社交媒体讨论'
        ],
        expectedOutcome: '及时发现市场异常波动'
      });
    }

    if (transaction.valueUSD > 50000000) {
      recommendations.push({
        id: `rec_${Date.now()}_2`,
        type: 'investigation',
        priority: 'medium',
        title: '深度调查',
        description: '建议对交易双方进行深度背景调查',
        actionItems: [
          '分析交易方历史行为',
          '检查资金来源合规性',
          '评估洗钱风险'
        ],
        expectedOutcome: '确保交易合规性'
      });
    }

    return recommendations;
  }

  /**
   * 收集交易数据点
   */
  private async collectTransactionDataPoints(transaction: Transaction): Promise<DataPoint[]> {
    return [
      {
        metric: '交易金额',
        value: transaction.valueUSD,
        unit: 'USD',
        trend: 'up'
      },
      {
        metric: '区块链',
        value: transaction.chain.toUpperCase()
      },
      {
        metric: '确认状态',
        value: transaction.confirmed ? '已确认' : '待确认'
      },
      {
        metric: '代币类型',
        value: transaction.tokenSymbol || '原生代币'
      }
    ];
  }

  /**
   * 生成交易摘要
   */
  private async generateTransactionSummary(
    transaction: Transaction, 
    insights: Insight[]
  ): Promise<string> {
    const amount = transaction.valueUSD.toLocaleString();
    const chain = transaction.chain.toUpperCase();
    const token = transaction.tokenSymbol || '原生代币';
    
    let summary = `检测到一笔价值$${amount}的${token}交易在${chain}网络上执行。`;

    if (transaction.fromLabel && transaction.toLabel) {
      summary += `资金从${transaction.fromLabel.label}转移到${transaction.toLabel.label}。`;
    }

    const highImpactInsights = insights.filter(i => i.impact === 'high');
    if (highImpactInsights.length > 0) {
      summary += '该交易具有较高的市场影响潜力，需要重点关注。';
    }

    return summary;
  }

  /**
   * 分析模式洞察
   */
  private async analyzePatternInsights(patterns: any[], address: string): Promise<Insight[]> {
    const insights: Insight[] = [];

    // 分析模式多样性
    if (patterns.length > 5) {
      insights.push({
        id: `insight_${Date.now()}_1`,
        type: 'trend',
        title: '复杂行为模式',
        description: `地址显示出${patterns.length}种不同的交易模式，表明其活动复杂多样`,
        impact: 'medium',
        confidence: 0.8,
        supportingData: [{ metric: '模式数量', value: patterns.length }]
      });
    }

    // 分析特定模式
    const defiPatterns = patterns.filter(p => p.type === 'defi_interaction');
    if (defiPatterns.length > 0) {
      insights.push({
        id: `insight_${Date.now()}_2`,
        type: 'opportunity',
        title: 'DeFi活跃用户',
        description: '该地址是DeFi生态的活跃参与者，可能对新协议感兴趣',
        impact: 'low',
        confidence: 0.7,
        supportingData: [{ metric: 'DeFi交互次数', value: defiPatterns.length }]
      });
    }

    return insights;
  }

  /**
   * 生成模式建议
   */
  private async generatePatternRecommendations(
    patterns: any[], 
    insights: Insight[]
  ): Promise<Recommendation[]> {
    const recommendations: Recommendation[] = [];

    const suspiciousPatterns = patterns.filter(p => p.type === 'anomaly');
    if (suspiciousPatterns.length > 0) {
      recommendations.push({
        id: `rec_${Date.now()}_1`,
        type: 'investigation',
        priority: 'high',
        title: '异常模式调查',
        description: '发现异常交易模式，建议进行详细调查',
        actionItems: [
          '分析异常交易的时间和金额',
          '检查相关地址背景',
          '评估风险等级'
        ],
        expectedOutcome: '识别潜在风险'
      });
    }

    return recommendations;
  }

  /**
   * 收集模式数据点
   */
  private async collectPatternDataPoints(patterns: any[]): Promise<DataPoint[]> {
    const patternTypes = patterns.map(p => p.type);
    const uniqueTypes = [...new Set(patternTypes)];

    return [
      {
        metric: '总模式数',
        value: patterns.length
      },
      {
        metric: '模式类型',
        value: uniqueTypes.length
      },
      {
        metric: '平均置信度',
        value: patterns.reduce((sum, p) => sum + p.confidence, 0) / patterns.length,
        unit: '%'
      }
    ];
  }

  /**
   * 生成模式摘要
   */
  private async generatePatternSummary(patterns: any[], insights: Insight[]): Promise<string> {
    let summary = `对地址进行了全面的行为模式分析，共识别出${patterns.length}种交易模式。`;

    const dominantPattern = patterns.sort((a, b) => b.confidence - a.confidence)[0];
    if (dominantPattern) {
      summary += `主要表现为${this.getPatternDescription(dominantPattern.type)}行为。`;
    }

    const riskInsights = insights.filter(i => i.type === 'risk');
    if (riskInsights.length > 0) {
      summary += '发现了一些需要关注的风险指标。';
    }

    return summary;
  }

  /**
   * 收集市场数据
   */
  private async collectMarketData(timeframe: string): Promise<any> {
    // 这里应该调用实际的市场数据API
    return {
      totalTransactions: Math.floor(Math.random() * 1000) + 100,
      totalVolume: Math.floor(Math.random() * 1000000000) + 100000000,
      topTokens: ['ETH', 'BTC', 'BNB'],
      volatility: Math.random() * 0.1
    };
  }

  /**
   * 分析市场洞察
   */
  private async analyzeMarketInsights(marketData: any): Promise<Insight[]> {
    const insights: Insight[] = [];

    if (marketData.volatility > 0.05) {
      insights.push({
        id: `insight_${Date.now()}_1`,
        type: 'risk',
        title: '市场高波动',
        description: `当前市场波动率为${(marketData.volatility * 100).toFixed(2)}%，处于较高水平`,
        impact: 'high',
        confidence: 0.8,
        supportingData: [{ metric: '波动率', value: marketData.volatility }]
      });
    }

    return insights;
  }

  /**
   * 生成市场建议
   */
  private async generateMarketRecommendations(insights: Insight[]): Promise<Recommendation[]> {
    const recommendations: Recommendation[] = [];

    const riskInsights = insights.filter(i => i.type === 'risk');
    if (riskInsights.length > 0) {
      recommendations.push({
        id: `rec_${Date.now()}_1`,
        type: 'alert_tuning',
        priority: 'medium',
        title: '调整风险参数',
        description: '基于当前市场环境，建议调整风险监控参数',
        actionItems: [
          '降低大额交易告警阈值',
          '增加波动率监控频率',
          '关注异常交易模式'
        ],
        expectedOutcome: '提高风险检测精度'
      });
    }

    return recommendations;
  }

  /**
   * 收集市场数据点
   */
  private async collectMarketDataPoints(marketData: any): Promise<DataPoint[]> {
    return [
      {
        metric: '24h交易数量',
        value: marketData.totalTransactions,
        trend: 'up'
      },
      {
        metric: '24h交易量',
        value: marketData.totalVolume,
        unit: 'USD'
      },
      {
        metric: '市场波动率',
        value: marketData.volatility,
        unit: '%'
      }
    ];
  }

  /**
   * 生成市场摘要
   */
  private async generateMarketSummary(marketData: any, insights: Insight[]): Promise<string> {
    let summary = `过去24小时内，监控到${marketData.totalTransactions}笔大额交易，`;
    summary += `总价值达${(marketData.totalVolume / 1000000).toFixed(0)}百万美元。`;

    const riskInsights = insights.filter(i => i.type === 'risk');
    if (riskInsights.length > 0) {
      summary += '市场表现出较高的波动性，需要密切关注。';
    } else {
      summary += '市场整体表现稳定。';
    }

    return summary;
  }

  /**
   * 分析风险洞察
   */
  private async analyzeRiskInsights(addresses: string[], riskFactors: any[]): Promise<Insight[]> {
    const insights: Insight[] = [];

    const highRiskAddresses = addresses.filter(addr => 
      riskFactors.some(factor => factor.address === addr && factor.riskScore > 70)
    );

    if (highRiskAddresses.length > 0) {
      insights.push({
        id: `insight_${Date.now()}_1`,
        type: 'risk',
        title: '高风险地址检测',
        description: `发现${highRiskAddresses.length}个高风险地址，需要重点监控`,
        impact: 'high',
        confidence: 0.9,
        supportingData: [{ metric: '高风险地址数', value: highRiskAddresses.length }]
      });
    }

    return insights;
  }

  /**
   * 生成风险建议
   */
  private async generateRiskRecommendations(insights: Insight[]): Promise<Recommendation[]> {
    const recommendations: Recommendation[] = [];

    const riskInsights = insights.filter(i => i.type === 'risk');
    if (riskInsights.length > 0) {
      recommendations.push({
        id: `rec_${Date.now()}_1`,
        type: 'action',
        priority: 'urgent',
        title: '风险处置',
        description: '立即对高风险地址采取防控措施',
        actionItems: [
          '将高风险地址加入监控列表',
          '提高相关交易告警级别',
          '准备风险报告提交监管部门'
        ],
        expectedOutcome: '有效控制风险扩散'
      });
    }

    return recommendations;
  }

  /**
   * 收集风险数据点
   */
  private async collectRiskDataPoints(addresses: string[], riskFactors: any[]): Promise<DataPoint[]> {
    return [
      {
        metric: '分析地址数',
        value: addresses.length
      },
      {
        metric: '风险因子数',
        value: riskFactors.length
      },
      {
        metric: '平均风险分',
        value: riskFactors.reduce((sum, f) => sum + f.riskScore, 0) / riskFactors.length,
        unit: '分'
      }
    ];
  }

  /**
   * 生成风险摘要
   */
  private async generateRiskSummary(insights: Insight[]): Promise<string> {
    const riskLevel = insights.filter(i => i.impact === 'high').length > 0 ? '高' : '中等';
    return `风险评估完成，当前风险等级为${riskLevel}。${insights.length}项风险指标需要关注。`;
  }

  /**
   * 计算整体置信度
   */
  private calculateOverallConfidence(insights: Insight[]): number {
    if (insights.length === 0) return 0;
    return insights.reduce((sum, insight) => sum + insight.confidence, 0) / insights.length;
  }

  /**
   * 生成交易标签
   */
  private generateTransactionTags(transaction: Transaction): string[] {
    const tags = ['大额交易', transaction.chain];
    
    if (transaction.valueUSD > 100000000) tags.push('超大额');
    if (transaction.fromLabel?.type) tags.push(transaction.fromLabel.type);
    if (transaction.toLabel?.type) tags.push(transaction.toLabel.type);
    
    return tags;
  }

  /**
   * 生成模式标签
   */
  private generatePatternTags(patterns: any[]): string[] {
    const tags = ['行为分析'];
    const types = [...new Set(patterns.map(p => p.type))];
    return [...tags, ...types];
  }

  /**
   * 获取模式描述
   */
  private getPatternDescription(type: string): string {
    const descriptions = {
      deposit: '充值',
      withdrawal: '提现',
      defi_interaction: 'DeFi交互',
      arbitrage: '套利',
      accumulation: '资金聚合',
      distribution: '资金分散',
      anomaly: '异常'
    };
    
    return descriptions[type as keyof typeof descriptions] || '未知';
  }

  /**
   * 清理缓存
   */
  public clearCache(): void {
    this.reportCache.clear();
    logger.debug('已清理报告生成缓存');
  }
} 